package com.cee.admin.common;

import com.cee.cache.redis.RedisUtils;
import com.cee.common.exception.GlobalException;
import com.cee.common.utils.StringUtils;
import com.cee.common.web.result.ResultCode;
import com.cee.domain.modules.pro.entity.ProReport;
import com.cee.domain.modules.sys.entity.User;
import com.cee.ds.common.utils.BasePrincipalUtils;
import com.cee.ds.modules.pro.service.IProReportService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.Optional;

/**
 * @author wsz
 * @since 2024/6/25
 */
public abstract class BaseProjApiController extends BaseController {

    @Autowired
    protected IProReportService reportService;

    @Autowired
    protected RedisUtils redisUtils;

    protected void checkProjReadPermission(Long projId) {
        if (projId == null) {
            return;
        }
        User user = BasePrincipalUtils.currentUser();
        if (user.getCityId() == null) {
            return;
        }
        String cacheKey = "perm:proj:" + projId;
        String cacheValue = Optional.ofNullable(redisUtils.get(cacheKey)).map(Object::toString).orElse(null);
        GlobalException exception = null;
        if (cacheValue == null) {
            ProReport report = reportService.getByIdOrEx(projId);
            if (!Objects.equals(user.getCityId(), report.getCityId())) {
                exception = new GlobalException(ResultCode.NOT_PERMISSION);
            }
            cacheValue = report.getBelongUser() + ":" + report.getCityId();
            redisUtils.set(cacheKey, cacheValue);
        } else if (!StringUtils.equals(user.getCityId().toString(), cacheValue.split(":")[1])){
            exception = new GlobalException(ResultCode.NOT_PERMISSION);
        }
        if (exception != null) {
            throw exception;
        }
    }
}
